import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { withRouter } from 'react-router'
import moment from 'moment';
import queryString from 'query-string'
import Crumbs from '../../components/common/Crumbs'
import { routes } from '../../router.js'
import ask from '../../serve/api';
import styles from './style.module.scss'
import { toast, ToastContainer } from 'react-toastify'
import Page from '../../components/common/Page'

class DecisionDetail extends Component {
  constructor(){
    super();
    this.state = {
      loadState : 'pending',
      contentData : {},
      // 页面类型
      pageType : '',
      // 页面类型下 具体文章id
      id : '',
      pathName: '',
      inpVal : '',
      comment : {
        show : false,
        params : {
          page : 1,
          pageSize : 10,
        },
        loadState : '',
        list : [],
      },
      submitInputShow : false,
    }

    this.submitBtn = React.createRef();
    this.inputbox = React.createRe
  }
  
  componentDidMount() {
    const {match} = this.props;
    const pageType = match.params.pageType;
    const id = match.params.id;
    this.setState({
      pageType,
      id,
    });

    const api = 'fetchOrg' + pageType.substring(0,1).toUpperCase() + pageType.substring(1) + 'Info';
    console.log('api:',api)
    this.fetchContentData(api, { id });
    
    if(pageType === 'decision'){
      const {comment} = this.state;
      comment.show = true;
      this.setState({
        comment
      },() => {
        this.fetchCommentData('fetchListDecisionComment', Object.assign({}, this.state.comment.params, { decisionId : id }) );
      });
    };
  }

  // 获取详情数据
  async fetchContentData(api, params){
    const {code, result} = await ask[api](params);
    try {
      if(code !== '000000'){
        throw new Error('数据出错');
      };
      if(result){
        this.setState({
          loadState : 'success',
          contentData : result,
        });
      }else{
        this.setState({
          loadState : 'error',
        });
      }
    } catch (error) {
      console.log(error);
      this.setState({
        loadState : 'error',
      });
    }
  }

  // 获取评论
  async fetchCommentData(api, params){
    const {comment} = this.state;
    const {code, result} = await ask[api](params);
    try {
      if(code !== '000000'){
        throw new Error('数据出错');
      };
      if(!result){
        comment.loadState = 'error';
        this.setState({
          comment,
        });
        return;
      };
      comment.loadState = 'success';
      comment.list = result;
      this.setState({
        comment,
      });

    } catch (error) {
      console.log(error);
      comment.loadState = 'error';
      this.setState({
        comment,
      });
    }
  }

  publishComment = ()=>{
    const {inpVal} = this.state;
    ask.postDecisionComment({
      // 决策调研id
      decisionId : 1,
      // 用户id
      id : 1,
    }).then(res => {
      console.log(res);
      alert('发送成功');
    }).catch(msg => {
      console.log(msg);
      alert('发送失败');
    });
  }

  // 监听评论框输入值
  onCommentInput = (e)=>{
    this.setState({
      inpVal :  e.target.value
    });
  }

  // 点击按钮提交
  submitQuestion = (e)=>{
    e.preventDefault();

    this.setState({
      submitInputShow : true,
    },()=>{
      const input = this.submitBtn.current.querySelector('input');
      input.click();
    });

  }

  // 文件上传
  submitChange = (e)=>{
    if(!e.currentTarget.files[0]) return;
    const {id} = this.state;
    let formData = new FormData();
    formData.append('fileName', e.currentTarget.files[0]);
    
    ask.uploadFile({
      id,
    }, {
      data : formData,
      headers: {'Content-Type': 'multipart/form-data;'},
    } ).then(res => {
      const {code} = res;
      if(code !== '000000') return;

      toast.success('上传成功!', {
        position: toast.POSITION.TOP_CENTER
      });

    }).catch(msg => {
      console.log(msg);
    }).finally(msg => {
      this.setState({
        submitInputShow : false,
      });
    });
  }

  // 点击分页按钮
  clickPageIndex = (contentPage)=>{
    const {comment, id} = this.state;
    comment.params.page = contentPage;
    this.setState({
      comment,
    },()=>{
      // 获取列表
      this.fetchCommentData('fetchListDecisionComment', Object.assign({}, this.state.comment.params, { decisionId : id }) );
    });
  }
  
  render() {
    const {
      loadState,
      contentData,
      comment,
      pageType,
      submitInputShow,
    } = this.state;

    const path = `/mainPage/${pageType}`;
    const oRoute = routes.filter(item => item.path === `/mainPage/${pageType}` )[0];
    const pathName = oRoute? oRoute.title : '';

    const crumbsList = [{
      name : '首页',
      path : '/mainPage/main',
    },{
      name : pathName,
      path : path,
    },{
      name : '详情',
      path : '',
    }];

    return (
      <div className={styles.decision}>
        {/* 面包屑 */}
        {/* <Crumbs list={crumbsList} /> */}
        <div className={styles.content}>
          { loadState === 'success' && (
              <div>
                {/* 内容区 */}
                <div className={styles.contxtwrap}>
                  <div className={styles.tit} dangerouslySetInnerHTML={{__html : contentData.title}}></div>
                  { (contentData.author || contentData.origin || contentData.public_at) && (
                    <div className={styles.subInfo}>
                      <span className={styles.left}>
                        {contentData.author && <i dangerouslySetInnerHTML={{__html : '作者：'+contentData.author}}></i>}
                        {contentData.origin &&<i dangerouslySetInnerHTML={{__html : '来源：'+contentData.origin}}></i>}
                      </span>
                      <span className={styles.right}>
                        <i dangerouslySetInnerHTML={{__html : '点击量：'+contentData.click_times}}></i>
                        {contentData.public_at && <i>{moment(contentData.public_at).format('YYYY-MM-DD')}</i>}
                      </span>
                    </div>
                  )}
                  <div className={styles.con} dangerouslySetInnerHTML={{__html : contentData.content}}></div>
                </div>
                {/* 操作按钮 */}
                <div className={styles.optswrap}>
                  <a onClick={this.submitQuestion} ref={this.submitBtn}>提交调查问卷 { submitInputShow && <input type="file" hidden onChange={this.submitChange} onClick={e => {e.stopPropagation()} } /> } </a>
                  { contentData.attach_url && <em className={styles.midline}></em>}
                  { contentData.attach_url && <a href={contentData.attach_url}>下载调查问卷</a>}
                </div>


                {/* 评论列表 */}
                { comment.show && 
                  <div>
                    {/* 评论框 */}
                    <div className={styles.inputwrap}>
                      <input className={styles.input} placeholder="请发表你的建议和想法吧" type="text" onChange={this.onCommentInput} />
                      <a className={styles.btn} onClick={this.publishComment}>发布</a>
                    </div>
                    <div className={styles.commentwrap}>
                      { comment.loadState === 'success' && !!comment.list.length &&
                        <ul className={styles.commentList}>
                          { comment.list.map((item, index) => (
                            <li key={index} className={styles.person}>
                              <span className={styles.name}>{item.title || item.name}：</span>
                              <div className={styles.conwrap}>
                                <div className={styles.con}>{item.content}</div>
                                <p className={styles.date}>{moment(item.public_at).format('YYYY-MM-DD')}</p>
                              </div>
                            </li>
                          ) ) }
                        </ul>
                      }
                      { comment.loadState === 'success' && !comment.list.length && <p>暂无评论列表</p> }
                      { comment.loadState === 'pending' && !comment.list.length && <p>评论加载中...</p> }
                      { comment.loadState === 'error' && !comment.list.length && <p>评论加载出错</p> }
                      { !!comment.totalPage && <Page 
                        pageConfig={{totalPage : comment.totalPage, currentPage : comment.params.page}}
                        pageCallbackFn={this.clickPageIndex}
                      />}
                    </div>
                  </div>
                }
                
              </div>
            ) }
          { loadState === 'pending' && <p className={styles.statetip}>正在查找...</p> }
          { loadState === 'error' && <p className={styles.statetip}>未找到该信息</p> }
        </div>
      </div>
    )
  }
}

export default withRouter(DecisionDetail);
